﻿using UnityEngine;
using System.Collections;

public class Button : MonoBehaviour
{
	public GameObject[] obstacleToDestroy;
	public bool moveX, moveY;
	public float valueToMoveButton = 0.11f;
	
	void OnTriggerEnter (Collider collider)
	{
		//Se o jogador ou uma pedra colidir com o botao.
		if (collider.transform.tag.Equals ("Player") || collider.transform.tag.Equals ("Rock")) {
			
			//Mover o botao para baixo e desativar todos os bloqueadores da chave.
			moveButton (true);
			StartCoroutine (DestroyObstacles (false));
		}
	}
	
	void OnTriggerExit (Collider collider)
	{
		if (collider.transform.tag.Equals ("Player") || collider.transform.tag.Equals ("Rock")) {
			moveButton (false);
			StartCoroutine (DestroyObstacles (true));
		}
	}
	
	IEnumerator DestroyObstacles (bool destroyObject)
	{
		int size = obstacleToDestroy.Length;
		int count = 0;
		
		while (count < size) {
			yield return new WaitForSeconds(.3f);
			
			EnabledObject (destroyObject, obstacleToDestroy [count]);
			count++;
		}
	}
	
	/// <summary>
	/// Deixa um determinado GameObject visivel ou invisivel.
	/// </summary>
	/// <param name='b'>
	/// O objeto ficara invisivel?
	/// </param>
	/// <param name='obj'>
	/// O objeto que sera alterado.
	/// </param>
	private void EnabledObject (bool b, GameObject obj)
	{
		obj.GetComponent<MeshRenderer> ().enabled = b;
		obj.GetComponent<BoxCollider> ().isTrigger = !b;
	}
	
	private void moveButton (bool triggerEnter)
	{
		if (triggerEnter) {
			
			if (moveX)
				transform.Translate (valueToMoveButton, 0, 0);
			else if (moveY)
				transform.Translate (0, valueToMoveButton, 0, Space.World);
			
		} else {
			if (moveX)
				transform.Translate (-valueToMoveButton, 0, 0);
			else if (moveY)
				transform.Translate (0, -valueToMoveButton, 0, Space.World);
		}
	}
}